import { WeeklyStory, getWeeklyList, saveWeekly, getLastWeekDiaries } from '../../models/diary'
import { generateUniqueId, formatDate, showToast } from '../../utils/util'
import { generateWeeklyStory } from '../../utils/api'

Page({
  data: {
    weeklyList: [] as WeeklyStory[],
    weekDiariesCount: 0,
    hasEnoughDiaries: false,
    generating: false
  },
  onLoad() {
    this.loadData()
  },
  onShow() {
    // 页面显示时刷新数据
    this.loadData()
  },
  // 加载数据
  loadData() {
    const weeklyList = getWeeklyList()
    const weekDiaries = getLastWeekDiaries()
    const weekDiariesCount = weekDiaries.length
    
    this.setData({
      weeklyList,
      weekDiariesCount,
      hasEnoughDiaries: weekDiariesCount >= 3
    })
  },
  
  // 生成周记故事
  generateWeeklyStory() {
    this.setData({ generating: true })
    
    generateWeeklyStory()
      .then(storyContent => {
        // 获取本周的开始和结束日期
        const now = new Date()
        const dayOfWeek = now.getDay() || 7
        
        const mondayOffset = 1 - dayOfWeek
        const mondayDate = new Date(now)
        mondayDate.setDate(now.getDate() + mondayOffset)
        
        const sundayOffset = 7 - dayOfWeek
        const sundayDate = new Date(now)
        sundayDate.setDate(now.getDate() + sundayOffset)
        
        // 创建周记对象
        const weekDiaries = getLastWeekDiaries()
        const weeklyStory: WeeklyStory = {
          id: generateUniqueId(),
          content: storyContent,
          startDate: formatDate(mondayDate),
          endDate: formatDate(sundayDate),
          diaryIds: weekDiaries.map(diary => diary.id),
          timestamp: Date.now()
        }
        
        // 保存周记
        const success = saveWeekly(weeklyStory)
        
        if (success) {
          showToast('生成周记成功', 'success')
          this.loadData()
        } else {
          showToast('保存周记失败', 'error')
        }
      })
      .catch(error => {
        console.error('生成周记失败', error)
        showToast('生成周记失败: ' + error.message, 'error')
      })
      .finally(() => {
        this.setData({ generating: false })
      })
  },
  
  // 跳转到写日记页面
  navigateToDiary() {
    wx.switchTab({
      url: '/pages/diary/diary'
    })
  },
  
  // 分享功能
  onShareAppMessage(e: any) {
    const id = e.target?.dataset?.id
    
    if (!id) {
      return {
        title: '梦迹日记 - 记录生活点滴，化作梦的痕迹',
        path: '/pages/index/index'
      }
    }
    
    const weeklyList = this.data.weeklyList
    const weekly = weeklyList.find(item => item.id === id)
    
    if (!weekly) {
      return {
        title: '梦迹日记 - 记录生活点滴，化作梦的痕迹',
        path: '/pages/index/index'
      }
    }
    
    // 分享特定的周记
    return {
      title: `我的一周故事：${weekly.startDate} ~ ${weekly.endDate}`,
      path: `/pages/weekly/weekly?id=${id}`,
      imageUrl: '/pages/images/share.png' // 自定义分享图片
    }
  }
}) 